import { http } from '@zh/common-utils/http'

import storage from '@zh/common-utils/utils/storage'

import { LOST_SESSION_CODE } from './constants'

import { exchangeToken } from './api/auth/index'

let handleHttpErrorTimestamp = null,
  handleHttpErrorModalInterval = null

const install = (Vue, router, store) => {
  Vue.prototype.http = http

  Object.assign(http, {
    exchangeToken,
    beforeLoad (config) {
      config.showLoading !== false && store.showLoading()
    },
    afterLoad (response) {
      store.hideLoading()
      if (response && response.data.code == 0 && response.config.handleMessage !== false) {
        // 拦截接口名称含有 save、update、delete 的接口，并提示操作成功
        const apiName = response.config.url.split('/').pop().toLowerCase()
        if (['save', 'update', 'delete'].find(str => apiName.includes(str))) {
          Vue.prototype.message && Vue.prototype.message.success('操作成功')
        }
      }
    },
    onError (e) {
      store.hideLoading()
      Vue.prototype.notify.error(e.message)
    },
    onLostSession (e) {
      store.hideLoading()
      Vue.prototype.notify.error(e.message, () => {
        router.redirectLogin()
      })
    },
    getEncryptor () {
      const encryptor = store.getAppConfig('_encryptor')
      if (encryptor) {
        return encryptor.default || encryptor
      }
      return null
    }
  })
}

export { http }

export default {
  install
}
